const DOMAIN = 'http://1.13.13.116';
const _DOMAIN = 'http://1.13.13.116'
const _URL = _DOMAIN + '/openapiv2/';
const API_URL = _URL + 'index/';
const ADMIN_USERID = 1; //用户id后台获取
const TipInfo = {
    data_error: '系统错误~',
    data_busy: '系统繁忙~',
    data_succuss: '成功~',
    data_fail: '失败~',
    data_login_succuss: '登录成功~',
    data_login_fail: '登录失败~',
};
const Gtablist = [{
    title: '淘宝',
    value: 'tb',
    bg: 'rgba(0,0,0,0.0)',
    bgSelected: 'widget://image/cate_bg.png'
}, {
    title: '京东',
    value: 'jd',
    bg: 'rgba(0,0,0,0.0)',
    bgSelected: 'widget://image/cate_bg.png'
}, {
    title: '拼多多',
    value: 'pdd',
    bg: 'rgba(0,0,0,0.0)',
    bgSelected: 'widget://image/cate_bg.png'
}, {
    title: '唯品会',
    value: 'vip',
    bg: 'rgba(0,0,0,0.0)',
    bgSelected: 'widget://image/cate_bg.png'
}, {
    title: '苏宁',
    value: 'sn',
    bg: 'rgba(0,0,0,0.0)',
    bgSelected: 'widget://image/cate_bg.png'
}];
const Gsortlist = [{
    name: '综合',
    sort: 0,
    type: 'tb'
}, {
    name: '销量',
    sort: 2,
    type: 'tb'
}, {
    name: '奖励',
    sort: 6,
    type: 'tb'
}, {
    name: '价格',
    sort: 4,
    type: 'tb'
}];
var sorts_data = {
    pageindex: 1,
    min_id: 1,
    back: 20,
    page: 1,
    sort: 1,
    iscoupon: 1,
    with_coupon: 1,
    isloaded: false
};
const DEFAULT_MENU = [{
        'title': '优选',
        'cid': 0,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '女装',
        'cid': 1,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '男装',
        'cid': 2,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '内衣',
        'cid': 3,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '美妆',
        'cid': 4,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '配饰',
        'cid': 5,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '鞋品',
        'cid': 6,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '箱包',
        'cid': 7,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '儿童',
        'cid': 8,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '母婴',
        'cid': 9,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '居家',
        'cid': 10,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '美食',
        'cid': 11,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '数码',
        'cid': 12,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '家电',
        'cid': 13,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    },
    /*{
           'title': '其他',
           'cid': 14,
           'bg': 'rgba(0,0,0,0.0)',
           'bgSelected': 'widget://image/cate_bg.png'
       },*/
    {
        'title': '车品',
        'cid': 15,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '文体',
        'cid': 16,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }, {
        'title': '宠物',
        'cid': 17,
        'bg': 'rgba(0,0,0,0.0)',
        'bgSelected': 'widget://image/cate_bg.png'
    }

];
const DEFAULT_MENU_TWO = [{
    'title': '优选',
    'cid': 0,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '女装',
    'cid': 1,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '母婴',
    'cid': 2,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '美妆',
    'cid': 3,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '居家',
    'cid': 4,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '鞋品',
    'cid': 5,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '美食',
    'cid': 6,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '文娱',
    'cid': 7,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '数码',
    'cid': 8,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '男装',
    'cid': 9,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '内衣',
    'cid': 10,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '箱包',
    'cid': 11,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '配饰',
    'cid': 12,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '户外',
    'cid': 13,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}, {
    'title': '家装',
    'cid': 14,
    'bg': 'rgba(0,0,0,0.0)',
    'bgSelected': 'widget://image/cate_bg.png'
}];
var appSetInfo = $api.getStorage('appSetInfo');
const SYSTEM_V = '1.0';
/*************缓存设置*************************/
var setStorage = function(k, v) {
        $api.setStorage(k, {
            value: v,
            time: Date.parse(new Date()) / 1000
        });

    }
    //获取缓存数据
var getStorage = function(k) {
        if (!appSetInfo) {
            appSetInfo = {
                    cache_time: 0
                } //默认0分钟不缓存
        }
        var value = $api.getStorage(k);
        if (value) {
            var time = Date.parse(new Date()) / 1000;
            if (time - value.time > parseInt(appSetInfo.cache_time) * 60) { //缓存时间已过
                $api.rmStorage(k); //删除过期缓存
                return '';
            } else {
                return value.value;
            }
        } else {
            return '';
        }
    }
    //获取APP设置
var getAppSet = function(cb) {
    if (api.connectionType == 'none') {
        openWinto('offline_win', 'widget://html/coupon_head', {
            name: '网呢?',
            url: 'widget://html/offline.html',
            css: 'aui-hide'
        });
    } else {
        postData(API_URL + "getAppSet", {}, function(ret, err) {
          console.log(JSON.stringify(ret));
            if (ret) {
                typeof cb == 'function' && cb(ret, err);
            } else {
                openWinto('offline_win', 'widget://html/coupon_head', {
                    name: '系统繁忙',
                    url: 'widget://html/offline.html'
                });
            }
        })
    }
}

//获取自定义页面
function getDiyContent() {
    var diycontent = getStorage('diycontent');
    if (!diycontent) {
        postData(API_URL + 'getDiyContent', {}, function(ret, err) {
            if (ret) {
                if (ret.code == 1) {
                    setStorage('diycontent', ret.data);
                    diycontent = ret.data;
                    if ($api.isArray(diycontent)) {
                        for (var i = 0; i < diycontent.length; i++) {
                            if (diycontent[i].diywin == api.winName || diycontent[i].diywin == api.frameName) {
                                if (diycontent[i].diyhtml.substring(0, 4) == 'http') {
                                    api.execScript({
                                        //name: api.apiname,
                                        frameName: api.frameName,
                                        script: openindexfenleiurl_new(diycontent[i].diyhtml)
                                    });

                                } else {
                                    $api.html($api.byId('diycontent'), diycontent[i].diyhtml);
                                }
                            }
                        }
                    }
                }
            }
        })
    } else {
        if ($api.isArray(diycontent)) {
            for (var i = 0; i < diycontent.length; i++) {
                if (diycontent[i].diywin == api.winName || diycontent[i].diywin == api.frameName) {
                    $api.html($api.byId('diycontent'), diycontent[i].diyhtml);
                }
            }
        }
    }

}





//打开新窗口name:窗口名称；URL窗口地址；data对象参数
function openWinto(name, url, data) {
    if (api.systemType == "ios") {
        var times = 0;
    } else {
        var times = 300;
    }
    data = typeof(data) == 'object' ? data : {};
    data.reload = data.reload || true;
    data.bounces = data.bounces || false;
    data.islogin = data.islogin || false;
    data.fromwin = data.fromwin || api.winName;
    if (data.islogin && !isLoginOr()) {
        openWinto('login_win', 'widget://html/my/login');
    } else {
        api.openWin({
            name: name,
            url: url + '.html',
            delay: times,
            slidBackType: 'edge',
            useWKWebView: true,
            allowEdit: true,
            overScrollMode: "always",
            reload: data.reload,
            bounces: data.bounces,
            pageParam: {
                data: data
            },
            animation: {
                type: 'movein'
            }
        });
    }

}


function showProgress(msg) {
    msg = msg || '加载中...'
    api.showProgress({
        title: msg
    });
}

function hideProgress() {
    api.hideProgress();
}

//提示
function showToast(text, location) {
    text = text || '加载中...';
    location = location || 'middle';
    api.toast({
        msg: text,
        location: location
    });
    return;
}

/*打开商品搜索页面*/
function doSearch() {
    openWinto('searchlist_win', 'widget://html/search_frame');
}

//html模板解析函数
function setDotTmpl(tmpl_id, div_id, data) {
    var temp_id = $api.byId(tmpl_id);
    var tmpdata = doT.template($api.text(temp_id));
    $api.html($api.byId(div_id), tmpdata(data));
}

//导航菜单
function setNavMenu(menu_id, top_y, items, param) {
    param = typeof(param) == 'object' ? param : {};
    param.style = param.style || 'horizontal';
    param.width = param.width || 60;
    param.selectedindex = param.selectedindex || 0;
    param.height = param.height || 42;
    var NVNavigationBar = api.require('NVNavigationBar');
    NVNavigationBar.open({
        rect: {
            x: 0,
            y: top_y,
            w: api.winWidth,
            h: param.height
        },
        styles: {
            orientation: param.style,
            bg: 'rgba(0,0,0,0.0)',
            bgAlpha: 1,
            font: {
                size: 14,
                sizeSelected: 15,
                color: '#FFFFFF',
                colorSelected: '#FFFFFF',
                alpha: 1,
                bold: true
            },
            itemSize: {
                w: param.width,
                h: param.height
            }
        },
        items: items,
        selectedIndex: param.selectedindex,
        fixedOn: api.frameName,
        fixed: true,
        id: menu_id
    }, function(ret, err) {
        if (ret.eventType == 'click') {
            api.setFrameGroupIndex({
                name: ret.id + '_frame_list',
                index: ret.index
            });
        }
    })
}

//菜单选择
function setNavMenuSelected(menu_id, index) {
    var NVNavigationBar = api.require('NVNavigationBar');
    NVNavigationBar.setSelected({
        id: menu_id,
        index: index,
        selected: true
    }, function(ret) {});
}

//post获取数据
function postData(url, data, callback) {
    data.login_devid = api.deviceId;
    data.admin_userid = ADMIN_USERID;
    //  data.returnAll = data.returnAll || false;
    data.appid = api.appId;
    if (typeof(api) == "undefined") {
        $.post(url, data, function(ret) {
            typeof callback == "function" && callback(ret);
        }, "json");
        return;
    }
    api.ajax({
        url: url,
        method: 'post',
        data: {
            values: data
        },
    }, function(ret, err) {
        typeof callback == "function" && callback(ret, err);
    });

}
//需要服务器登录状态
function postDataisLogin(cb) {
    var userinfo = isLoginOr();
    if (userinfo) {
        postData(_URL + 'User/index', {
            userid: userinfo.id,
        }, function(ret, err) {
            if (ret && ret.code == 1) { //已登录
                typeof cb == 'function' && cb();
            } else {
                $api.rmStorage('taobao_user'); //删除缓存重新登录
                location.reload();
                openWinto('login_win', 'widget://html/my/login');
            }
        });
    } else {
        openWinto('login_win', 'widget://html/my/login');
    }
}

function postDataLogin(apiname, data, callback, files) {
    data.login_devid = api.deviceId;
    data.admin_userid = ADMIN_USERID;
    console.log(_URL + 'User/' + apiname);
    api.ajax({
        url: _URL + 'User/' + apiname,
        method: 'post',
        data: {
            values: data,
            files: files
        },
    }, function(ret, err) {
      console.log(JSON.stringify(ret));
      console.log(JSON.stringify(err));
        hideProgress(); //其他页面可能有showProgress();
        if (ret) {
            if (ret.code == 'relogin') {
                $api.rmStorage('taobao_user'); //删除缓存重新登录
                location.reload();
                openWinto('login_win', 'widget://html/my/login');
            } else {
                typeof callback == "function" && callback(ret, err);
            }
        } else {
            showToast(TipInfo.data_busy);
        }
    });
}
//get获取数据
function getData(url, cb) {
    url = url + '&login_devid=' + api.deviceId;
    api.ajax({
        url: url,
        method: 'get',
        cache: true,
    }, function(ret, err) {
      // console.log(JSON.stringify(err));
      // console.log(JSON.stringify(ret));
        typeof cb == 'function' && cb(ret, err)
    });

}
//第二接口获取数据
function getDataApiTwo(param, cb) {
    var apiurl = (appSetInfo.url_pingtai.two).replace('#apiname#', param.apiname);
    if (param.post == true) {
        apiurl = 'https://m.zhimatuiguangzhe.cn/api/' + param.apiname;
        delete param.apiname;
        param.appkey = appSetInfo.zhetaokeappkey;
        param.sid = appSetInfo.sid;
        postData(apiurl, param, function(ret, err) {
            typeof cb == 'function' && cb(ret, err);
        });
    } else {
        var url = '';
        for (var i in param) {
            if (i != 'apiname')
                url += i + '=' + param[i] + '&';
        }
        getData(apiurl + url, function(ret, err) {
            typeof cb == 'function' && cb(ret, err);
        });
    }
}

//第二接口商品
function getGoodsListByApiTwo(apiname, param, cb, more, tmpl_id, div_id) {
    param.dataisend = param.dataisend ? param.dataisend : sorts_data.dataisend || false;
    if (param.dataisend === true) {
        return false;
    }
    $(".temporarily_data").hide();
    $(".index_loading").show();
    more = more || false;
    tmpl_id = param.tmpl_id || 'tmpl_goods_list';
    div_id = param.div_id || 'div_goods_list';
    apiname = apiname || 'api_all.ashx';
    param.page = param.page || 1;
    param.page_size = param.page_size || sorts_data.back;
    param.output = param.output || true;
    var url = '';
    for (var i in param) {
        url += i + '=' + param[i] + '&';
    }
    url = (appSetInfo.url_pingtai.two + url).replace('#apiname#', apiname);
    getData(url, function(ret, err) {
        if (ret) {
            console.log(JSON.stringify(err));
            if (ret.status == 200) {
                $(".temporarily_data").hide();
                $(".index_loading").hide();
                for (var i in ret.content) {
                    if (ret.content[i].jianjie) {
                        ret.content[i].jianjie = ret.content[i].jianjie.length < 4 ? ret.content[i].tao_title : ret.content[i].jianjie;
                        ret.content[i].jianjie = ret.content[i].jianjie.replace(/\r\n/g, "");
                    }

                    ret.content[i].biaoqian = '';
                }

                if (param.output === true) { //是否需要渲染模板
                    if (true === more) {
                        var list_data = new Array;
                        var temp_id = $api.byId(tmpl_id);
                        var tmpdata = doT.template($api.text(temp_id));
                        list_data = list_data.concat(ret.content);
                        $api.append($api.byId(div_id), tmpdata(list_data));
                    } else {
                        setDotTmpl(tmpl_id, div_id, ret.content);
                        imgload();
                    }
                } else {
                    typeof cb == 'function' && cb(ret, err);
                }
            } else {
                sorts_data.dataisend = true;
                $(".index_loading").hide();
                if (param.page == 1) {
                    $(".temporarily_data").show();
                } else {
                    $(".index_loading img").hide();
                    $(".index_loading span").html("<div style='padding-left:30px;color:#dddddd'>—这是我的底线—</div>");
                    $(".index_loading").show();
                }
            }
        } else {
            showToast(TipInfo.data_busy);
        }
    });
}

//第一接口商品
function getGoodsListByApiOne(apiname, param, cb, more, tmpl_id, div_id) {
    param.dataisend = param.dataisend ? param.dataisend : sorts_data.dataisend || false;
    param.isshownodata = param.isshownodata == 'false' ? 'false' : true;
    if (param.dataisend === true) {
        return false;
    }
    $(".temporarily_data").hide();
    $(".index_loading").show();
    more = more || false;
    tmpl_id = param.tmpl_id || 'tmpl_goods_list';
    div_id = param.div_id || 'div_goods_list';
    apiname = apiname || 'itemlist';
    param.min_id = param.min_id || 1;
    param.back = param.back || sorts_data.back;
    param.output = param.output || true;
    var url = '';
    for (var i in param) {
        url += i + '=' + param[i] + '&';
    }
    var APP_URL_ONE = (appSetInfo.url_pingtai.one + url).replace('#apiname#', apiname);
    getData(APP_URL_ONE, function(ret, err) {
        if (ret) {
            if (ret.code == 1 && (ret.data && ret.data.length > 0 || ret.item_info && ret.item_info.length > 0 || ret.data.items && ret.data.items.length > 0)) {
                $(".temporarily_data").hide();
                sorts_data.min_id = parseInt(ret.min_id) < 1 ? 9999 : ret.min_id;
                sorts_data.tb_p = ret.tb_p;
                sorts_data.count = 1;
                if (param.output === true) { //是否需要渲染模板
                    if (true === more) {
                        var list_data = new Array;
                        var temp_id = $api.byId(tmpl_id);
                        var tmpdata = doT.template($api.text(temp_id));
                        list_data = list_data.concat(ret.data);
                        $api.append($api.byId(div_id), tmpdata(list_data));
                    } else {
                        setDotTmpl(tmpl_id, div_id, ret.data);
                        imgload();
                    }
                }
                $(".index_loading").hide();
                typeof cb == 'function' && cb(ret, err);
            } else { //无数据
                console.log(JSON.stringify(sorts_data));
                sorts_data.dataisend = true;
                $(".index_loading").hide();
                if (param.min_id == 1 && param.isshownodata == true) {
                    $(".temporarily_data").show();
                } else {
                    $(".index_loading img").hide();
                    $(".index_loading span").html("<div style='padding-left:30px;color:#dddddd'>—这是我的底线—</div>");
                    $(".index_loading").show();
                }
            }
        } else { //获取数据错误重试
            sorts_data.count++;
            if (sorts_data.count <= 4) {
                getGoodsListByApiOne(apiname, param, cb, more);
            } else {
                $(".index_loading").hide();
                showToast('系统繁忙~');
            }
        }
    });
}
//商品列表接口
/*********
apiname 接口名称string
param 接口参数obeject
cb 回调函数
tmpl_id 模板id string
div_id  htmlid string
more  加载更多 string
*************/
function getGoodsList(apiname, param, cb, more, tmpl_id, div_id) {
    param.pingtai = appSetInfo.pingtai || 1;
    switch (param.pingtai) {
        case 1:
            getGoodsListByApiOne(apiname, param, cb, more, tmpl_id, div_id);
            break;
        case 2:
            getGoodsListByApiTwo(apiname, param, cb, more, tmpl_id, div_id);
            break;
        default:

    }


}

//分类筛选商品
function getSortGoods(tabs, callback) {
    tabs = tabs || 'sorts';
    var tab = new auiTab({
        element: document.getElementById(tabs),
    }, function(ret) {
        gotoback(); //当页面在底端时候，切换时候就返回顶端
        typeof callback == 'function' && callback(ret);
    });
}

//滑动到底部加载更多
function getMoreGoods(callback) {
    api.addEventListener({
        name: 'scrolltobottom',
        extra: {
            threshold: 20
        }
    }, function(ret, err) {
        typeof callback == "function" && callback();
    });
}

//根据商品itemid获取商品详情
var getGoodDetail = function(param, cb) {
    param = typeof(param) == 'object' ? param : {};
    param.apiname = param.apiname || 'getGoodDetail';
    param.source_type = param.source_type || 'tb';
    if (param.source_type == 'sn') {
        postData(_URL + 'Sn/getSuningDetail', {
            id: param.goods_id
        }, function(ret, err) {
            typeof cb == 'function' && cb(ret, err);
        })
    } else if (param.source_type == 'vip') {
        postData(_URL + 'Vip/getVipDetail', {
            goodid: param.goods_id
        }, function(ret, err) {
            typeof cb == 'function' && cb(ret, err);
        })
    } else if (param.source_type == 'mgj') {
        postData(_URL + 'Mg/goodsdetail', {
            goodid: param.goods_id
        }, function(ret, err) {
            typeof cb == 'function' && cb(ret, err);
        })
    } else {
        postData(appSetInfo.url_pingtai.three + param.source_type + '/goodsdetail', {
            goods_id: param.goods_id
        }, function(ret, err) {
            if (ret) {
                typeof cb == 'function' && cb(ret, err);
            } else {
                postData(_URL + param.source_type + '/goodsdetail', param, function(ret, err) {
                    typeof cb == 'function' && cb(ret, err);
                });
            }
        });
    }


}

//淘宝图文详情
function getTaoBaoDetail(itemid, desc_img) {
    $("#tabtxt").html('商品图文详情（加载中......）');
    $.ajax({
        url: tb_url,
        tryCount: 0,
        retryLimit: 3,
        dataType: 'jsonp',
        jsonpCallback: 'mtopjsonp1',
        success: function(dat) {
          // console.log(JSON.stringify(dat));
            if (dat.ret[0] == "SUCCESS::调用成功") {
                var picinfo = dat.data.pcDescContent;
                var patt = /<img[^>]+src=['"]([^'"]+)['"]+/g;
                var image = [],
                    temp;
                while ((temp = patt.exec(picinfo)) != null) {
                    if (temp[1].indexOf('img.alicdn.com') !== -1) {
                        image.push("<img src='https:" + temp[1] + "' style='width:100%;max-width:100%' onerror='this.src=../image/load-img.png' class='bgimg'>");
                    }
                }
                $("." + desc_img).html(image);
                $("#tabtxt").html('商品图文详情（加载完毕，请您查阅）');
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            this.tryCount++;
            $("#tabtxt").html('商品图文详情（加载中' + this.tryCount + '......）');
            $.ajax(this);
            return;
        }
    });

}
//下拉刷新
function pullDown(cb, pram) {
    if (!pram) {
        api.setRefreshHeaderInfo({
            loadingImg: 'widget://image/sx.png',
            bgColor: 'rgba(0,0,0,0.0)',
            textColor: '#fff',
            textDown: '下拉刷新...',
            textUp: '松开刷新...'
        }, function(ret, err) {
            typeof cb == 'function' && cb();
            api.refreshHeaderLoadDone();
        });
    } else if (pram === true) {
        api.setRefreshHeaderInfo({
            bgColor: 'rgba(0,0,0,0.0)',
            textDown: '下拉刷新...',
            textUp: '松开刷新...'
        }, function(ret, err) {
            typeof cb == 'function' && cb();
            api.refreshHeaderLoadDone();
        });
    } else {
        api.setRefreshHeaderInfo({
            loadingImg: 'widget://image/cate_bg.png',
            bgColor: 'rgba(0,0,0,0.0)',
            textColor: '#fff',
            textDown: '',
            textUp: ''
        }, function(ret, err) {
            typeof cb == 'function' && cb();
            api.refreshHeaderLoadDone();
        });
    }
}

//打开远程页面
function openWinX5(param, cb) {
    if (!param.url) {
        return;
    }
    param.x = param.x || 0;
    param.y = param.y || 0;
    param.w = param.w || 'auto';
    param.h = param.h || 'auto';
    param.marginBottom = param.marginBottom || 0;
    param.headers = param.headers || {};
    var browser = api.require('webBrowser');
    browser.openView({
        url: param.url,
        headers: param.headers,
        rect: {
            x: param.x,
            y: param.y,
            w: param.w,
            h: param.h,
            marginLeft: 0,
            marginTop: 0,
            marginBottom: param.marginBottom,
            marginRight: 0
        }
    }, function(ret, err) {
        typeof cb == 'function' && cb(ret, err);
    });
}

//打开远程网页
function openUrlX5(url) {
    var browser = api.require('webBrowser');
    browser.open({
        url: url
    });
}
var webGoBack = function() {
    var browser = api.require('webBrowser');
    browser.historyBack(
        function(ret, err) {
            if (!ret.status) {
                if (api.winName == 'taobaologin_win' && (api.pageParam.data.fromwin == 'detail_win' || api.pageParam.data.fromwin == 'pdd_jd_detail_win')) {
                    var js = 'location.reload();';
                    getUserAllInfo(function(ret, err) {
                        if (ret.code == 1) {
                            api.execScript({
                                name: api.pageParam.data.fromwin,
                                script: js
                            });
                            api.closeWin();
                        }
                    });
                } else {
                    api.closeWin();
                }
            }
        }
    );
}

//缓存图片
function imageCache(_el, data) {
    data = typeof(data) == 'object' ? data : {};
    data.src = data.src || 'src';
    data.thumbnail = data.thumbnail === false ? false : true;
    api.imageCache({
        url: $api.attr(_el, data.src),
        thumbnail: data.thumbnail
    }, function(ret, err) {
        if (ret) {
            if (ret.status == true) {
                $api.attr(_el, data.src, ret.url);
            }
        }
    });

}
//缓存图片
function iCache(selector, bg) {
    bg = bg || '../image/load-img.png';
    selector.each(function(data) {
        ! function(data) {
            var url = selector.eq(data).attr("src");
            var img = this;
            var pos = url.lastIndexOf("/");
            var filename = url.substring(pos + 1);
            var path = api.cacheDir + "/pic/" + filename;
            var obj = api.require('fs');
            selector.eq(data).attr('src', bg);
            obj.exist({
                path: path
            }, function(ret, err) {
                if (ret.exist) {
                    if (ret.directory) {} else {
                        //selector.eq(data).attr('src', null);
                        path = api.cacheDir + "/pic/" + filename;
                        selector.eq(data).attr('src', path);
                    }
                } else {
                    api.download({
                        url: url,
                        savePath: path,
                        report: false,
                        cache: true,
                        allowResume: true
                    }, function(ret, err) {
                        if (ret.state == 1) {
                            selector.eq(data).attr('src', ret.savePath);
                        }
                    });
                }
            });
        }(data);
    });
}

function GetUrlParam(url, paraName) {　　　　
    var arrObj = url.split("?");　　　　
    if (arrObj.length > 1) {　　　　　　
        var arrPara = arrObj[1].split("&");　　　　　　
        var arr;　　　　　　
        for (var i = 0; i < arrPara.length; i++) {　　　　　　　　
            arr = arrPara[i].split("=");
            if (arr != null && arr[0] == paraName) {　　　　　　　　　　
                return arr[1];　　　　　　　　
            }　　　　　　
        }　　　　　　
        return "";　　　　
    }　　　　
    else {　　　　　　
        return "";　　　　
    }　　
}

//页面左右滑动防止swiper不动
function setAppNotSroll() {
    api.addEventListener({
        name: 'swipeleft'
    }, function(ret, err) {
        api.setFrameGroupAttr({
            name: 'index_frame_list',
            scrollEnabled: true
        });
    });
    api.addEventListener({
        name: 'swiperight'
    }, function(ret, err) {
        api.setFrameGroupAttr({
            name: 'index_frame_list',
            scrollEnabled: true
        });
    });
}
//页面上滑隐藏页头
function bodySrollChangeHeader(frmid) {
    getDiyContent(); //获取自定义页面
    window.onscroll = function() {
        var toph = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
        if (toph > 300) {
            $api.css($api.byId('gotoback'), "display:block");
        } else {
            $api.css($api.byId('gotoback'), "display:none");
        }
        if (frmid) {
            var func = 'changeHeader(' + toph + ',' + frmid + ');';
            api.execScript({
                name: 'root',
                frameName: 'index_win',
                script: func
            });
        }
    }
}
//返回页面顶部
function gotoback() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
}

//首页分类
function openindexfenleiurl_new(url, type) {
    if (api.connectionType == "none") {
        showToast("网络出差~");
    } else {
        var param = url.substring(0, 4);
        if (param == 'open') { // open开头打开内页;
            url = url.replace(/#/g, "'");
            api.execScript({
                frameName: 'index_frame_0',
                script: url
            });
        } else if (param == 'http') {
            if (type == 'openbybc') {
                fun.bc.showTaobaopage(url);
            } else {
                openWinto('web_view_win', 'widget://html/web_view_head', {
                    url: url
                });
            }

        } else if (param == 'url_') { //活动需要重新转链的
            var new_url = url.split('_'); //new_url[1]为活动id
            getTaoBaoHuoDongUrl(new_url[1]);
        }
    }
}
//验证商品url是京东、拼多多、淘宝 返回 jd、pdd、tb
var checkurlPlatform = function(url) {
    if (url.indexOf('jd.') > 0) {
        return 'jd';
    }
    if (url.indexOf('yangkeduo.com') > 0) {
        return 'pdd';
    }
    if (url.indexOf('taobao.com') > 0 || url.indexOf('tb.cn') > 0) {
        return 'tb';
    }
    if (url.indexOf('tmall.com') > 0) {
        return 'tb';
    }
    if (url.indexOf('suning.com') > 0) {
        return 'sn';
    }
    if (url.indexOf('vip.com') > 0) {
        return 'vip';
    }
    if (url.indexOf('mogu.com') > 0) {
        return 'mgj';
    }
}
var getQueryKey = function(url, key) {
        var theRequest = [];
        if (url.indexOf("?") != -1) {
            var str = url.split('?')[1];
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                if (strs[i].split("=")[0] && unescape(strs[i].split("=")[1])) {
                    theRequest[i] = {
                        'name': strs[i].split("=")[0],
                        'value': unescape(strs[i].split("=")[1])
                    }
                }
            }
        }
        var keyvalue = "";
        for (var j = 0; j < theRequest.length; j++) {
            if (theRequest[j] && theRequest[j].name == key) {
                keyvalue = theRequest[j].value;
            }
        }
        if (keyvalue.indexOf('#') > 0) {
            keyvalue = keyvalue.split(',')[0];
        }
        return keyvalue;
    }
    //获取商品id
var getGoodId = function(platform, url) {
        var itemid = "";
        switch (platform) {
            case 'tb':
                itemid = getQueryKey(url, 'id');
                if (itemid == "") {
                    itemid = getQueryKey(url, 'item_id');
                }
                return (itemid);
                break;
            case 'jd':
                itemid = getQueryKey(url, 'sku');
                if (itemid == "") {
                    itemid = getQueryKey(url, 'wareId');
                    if (itemid == "") {
                        url = url.split('?')[0];
                        var strlist = url.split('/');
                        var skuidstr = strlist[strlist.length - 1];
                        if (skuidstr.indexOf('.') > 0 && skuidstr.indexOf('index') < 0) {
                            itemid = skuidstr.split(".")[0];
                        }
                    }
                }
                return (itemid);
                break;
            case 'pdd':
                itemid = getQueryKey(url, 'goods_id');
                return (itemid);
                break;
            case 'sn':
                itemid = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf('.html'));
                var regPos = /^\d+(\.\d+)?$/; //非负浮点数
                var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
                if (regPos.test(itemid) || regNeg.test(itemid)) {

                } else {
                    itemid = "";
                }
                return (itemid);
                break;
            case "vip":
                itemid = getQueryKey(url, 'productId');
                if (itemid == "") {
                    if (url.indexOf("product-") > 0) {
                        itemid = url.substring(url.lastIndexOf("-") + 1, url.lastIndexOf('.html'));
                        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
                        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
                        if (regPos.test(itemid) || regNeg.test(itemid)) {

                        } else {
                            itemid = "";
                        }
                    }
                }
                return (itemid);
                break;
            case "mgj":
                itemid = getQueryKey(url, 'itemId');
                return (itemid);
                break;
        }

    }
    //提取内容中的链接
var getContentUrls = function(s) {
        //  var reg = /(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|&|-)+)/g;
        var reg = /(https?|http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
        s = s.match(reg);
        return (s)
    }
    //提取内容中的口令
var getContentKouling = function(s) {
        var substr = s.match(/(?=.*[a-zA-Z])[a-zA-Z0-9]{11}/); //s.match(/([a-zA-Z0-9]{11})/); //s.match(/￥(\S*)￥/);
        return (substr);
    }
    //检查粘贴板
function checkClipboard(cb) {
    var clipBoard = api.require('clipBoard');
    clipBoard.get(function(ret, err) {
        if (ret) {
            if (ret.value.substring(0, 3) == 'Tip') {
                return;
            } else {
                clipBoard.set({
                    value: ''
                });
            }
            var url = getContentUrls(ret.value);
            var kouling = getContentKouling(ret.value);
            if (url !== null && kouling !== null) {
                kouling = null;
            }
            if (url !== null) {
                showTips({
                    title: '检测到网址是否转链?',
                    content: url[0],
                    topImage: 'widget://image/url_bg.png',
                    buttons: [{
                        normal: 'widget://image/quxiao.png',
                        highlight: 'widget://image/quxiao.png',
                    }, {
                        normal: 'widget://image/quding.png',
                        highlight: 'widget://image/quding.png',
                    }],
                    buttonstyle: [{
                        iconSize: 45,
                        textColor: '#000',
                        textSize: 1,
                        marginT: 0,
                        space: 50
                    }, {
                        iconSize: 45,
                        textColor: '#000',
                        textSize: 1,
                        marginT: 0,
                        space: 50
                    }]
                }, function(ret) {
                    switch (ret.index) {
                        case 0:
                            closeDialogBox('tips');
                            break;
                        case 1:
                            openWinto('web_view_win', 'widget://html/web_view_head', {
                                url: url[0]
                            });
                            break;
                        default:

                    }
                });
            } else if (kouling !== null) {
                showTips({
                    title: '检测到淘口令是否解析?',
                    content: '￥' + kouling[0] + '￥',
                    topImage: 'widget://image/url_bg.png',
                    buttons: [{
                        normal: 'widget://image/quxiao.png',
                        highlight: 'widget://image/quxiao.png',
                    }, {
                        normal: 'widget://image/quding.png',
                        highlight: 'widget://image/quding.png',
                    }],

                    buttonstyle: [{
                        iconSize: 45,
                        textColor: '#000',
                        textSize: 1,
                        marginT: 0,
                        space: 50
                    }, {
                        iconSize: 45,
                        textColor: '#000',
                        textSize: 1,
                        marginT: 0,
                        space: 50
                    }]
                }, function(ret) {
                    switch (ret.index) {
                        case 0:
                            closeDialogBox('tips');
                            break;
                        case 1:
                            showProgress('解析中~');
                            getDataApiTwo({
                                apiname: 'open_shangpin_id.ashx',
                                content: encodeURI('￥' + kouling[0] + '￥'),
                                type: 1
                            }, function(ret, err) {
                                hideProgress();
                                if (ret.item_id) {
                                    openWinto('web_view_win', 'widget://html/web_view_head', {
                                        url: 'https://item.taobao.com/item.htm?id=' + ret.item_id
                                    });
                                } else {
                                    showToast('淘口令已失效!');
                                }
                            });
                            break;
                        default:

                    }
                });
            } else if (ret.value.trim() != "") {
                showTips({
                    content: ret.value,
                    tapClose: true
                }, function(rets) {
                    switch (rets.index) {
                        case 0:
                            openWinto('search_frame_win', 'widget://html/search_frame', {
                                source_type: 'tb',
                                keyword: ret.value
                            })
                            break;
                        case 1:
                            openWinto('search_frame_win', 'widget://html/search_frame', {
                                source_type: 'jd',
                                keyword: ret.value
                            })
                            break;
                        case 2:
                            openWinto('search_frame_win', 'widget://html/search_frame', {
                                source_type: 'pdd',
                                keyword: ret.value
                            })
                            break;
                    }
                });

            }

            typeof cb == "function" && cb(ret);
            //console.log(JSON.stringify(ret));
        }
    });
}

var showTips = function(param, cb) {
    var dialogBox = api.require('dialogBox');
    var buttons = [{
        normal: 'widget://image/icon_tb.png',
        highlight: 'widget://image/icon_tb.png',
        text: '淘宝'
    }, {
        normal: 'widget://image/icon_jd.png',
        highlight: 'widget://image/icon_jd.png',
        text: '京东'
    }, {
        normal: 'widget://image/icon_pdd.png',
        highlight: 'widget://image/icon_pdd.png',
        text: '拼多多'
    }];
    var buttonstyle = [{
        iconSize: 45,
        textColor: '#000',
        textSize: 12,
        marginT: 15,
        space: 25
    }, {
        iconSize: 45,
        textColor: '#000',
        textSize: 12,
        marginT: 15,
        space: 25
    }, {
        iconSize: 45,
        textColor: '#000',
        textSize: 12,
        marginT: 15,
        space: 25
    }];
    param.title = param.title || '是否搜索商品?';
    param.content = param.content || '';
    param.buttons = param.buttons || buttons;
    param.topImage = param.topImage || 'widget://image/search_banner.jpg';
    param.buttonstyle = param.buttonstyle || buttonstyle;
    dialogBox.tips({
        rect: {
            w: api.winWidth * 2.2 / 3
        },
        texts: {
            title: param.title,
            content: param.content
        },
        buttons: param.buttons,
        styles: {
            bg: '#FFF',
            topImage: {
                path: param.topImage,
                w: api.winWidth * 2.2 / 3,
                h: api.winWidth * 1.1 / 3
            },
            title: {
                color: '#000',
                size: 16,
                marginT: 15
            },
            content: {
                color: '#000',
                size: 14,
                marginT: 15
            },
            border: {
                color: '#eee',
                width: 2,
                marginT: 10
            },
            buttons: param.buttonstyle
        },
        tapClose: param.tapClose == true ? true : false,
        animation: true
    }, function(ret) {
        closeDialogBox('tips');
        typeof cb == "function" && cb(ret);
    });
}

var closeDialogBox = function(name) {
    var dialogBox = api.require('dialogBox');
    dialogBox.close({
        dialogName: name
    });
}

/******************************userinfo********************************/
/************ 判断是否登录.默认登录60分钟 ****************/
function isLogin() {
    var Taobao_UserInfo = $api.getStorage('taobao_user');
    console.log(JSON.stringify(Taobao_UserInfo));
    if (Taobao_UserInfo) {
        return Taobao_UserInfo;
    } else {
        openWinto('login_win', 'widget://html/my/login');
    }
}

function isLoginOr() {
    var Taobao_UserInfo = $api.getStorage('taobao_user');
    if (Taobao_UserInfo) {
        return Taobao_UserInfo;
    } else {
        return false;
    }
}
//获取用户所有信息
function getUserAllInfo(cb) {
    var login = isLoginOr();
    var tryCount = 1;
    //console.log(JSON.stringify(login));
    if (login) {
        postDataLogin('getUserInfo', {}, function(ret, err) {
            console.log(JSON.stringify(ret));
            console.log(JSON.stringify(err));
            if (ret.code == 1) {
                $api.setStorage('taobao_user', ret.data);
                typeof cb == "function" && cb(ret, err);
            } else if (ret.code == -1) {
                showToast(ret.msg);
            } else if (ret.code == 'relogin') {
                $api.rmStorage('taobao_user');
                showToast(ret.msg);
            } else {
                tryCount++;
                if (tryCount < 4) {
                    getUserAllInfo(cb);
                } else {
                    showToast(TipInfo.data_error);
                }
            }
        });
    } else {
        openWinto('login_win', 'widget://html/my/login');
    }
}

//下载图片
function downloadFile($fileurl, cb) {
    if (!$fileurl) {
        return;
    }

    showProgress('下载图片中...');
    //生成本地文件名
    $localfile = $fileurl.split('/');
    $filename = $localfile[$localfile.length - 1];
    $localpath = 'fs://yqlm/' + $filename;
    api.download({
        url: $fileurl,
        savePath: $localpath,
        report: true,
        cache: true,
        allowResume: true
    }, function(ret, err) {
        if (ret.state == 1) {
            var savePath = ret.savePath;
            api.saveMediaToAlbum({
                path: ret.savePath
            }, function(ret, err) {
                if (ret && ret.status) {
                    ret.savePath = savePath;
                    hideProgress();
                    typeof cb == "function" && cb(savePath);

                } else {}
            });
        } else {}
    });

}

//打开app
function openApp(param) {
    api.openApp({
        iosUrl: param.iosUrl,
        androidPkg: param.appPkg || 'android.intent.action.VIEW',
        mimeType: 'text/html',
        uri: 'intent://' + param.uri + '#Intent;scheme=' + param.scheme + ';package=' + param.appname + ';end'
    }, function(ret, err) {});
}

function openAppUrl(type, url) {
    switch (type) {
        case 'tb':
            if (appSetInfo.taobaotype == 2) { //是否百川掉起淘宝
                fun.bc.showTaobaopage(url);
            } else {
                openApp({
                    iosUrl: 'taobao://' + url.replace('https://', ''),
                    appname: 'com.taobao.taobao',
                    scheme: 'taobao',
                    uri: url.replace('https://', '')
                });
            }
            break;
        case 'jd':
            openApp({
                iosUrl: 'openApp.jdMobile://virtual?params=' + encodeURIComponent('{"des":"m","url":"' + url + '","category":"jump"}'),
                appname: 'com.jingdong.app.mall',
                scheme: 'openApp.jdMobile://virtual?params=' + encodeURIComponent('{"des":"m","url":"' + url + '","category":"jump"}'),
                uri: 'm.jd.com/',
            });
            break;
        case 'pdd':
            openApp({
                iosUrl: 'pinduoduo://com.xunmeng.pinduoduo/' + url,
                appname: 'com.xunmeng.pinduoduo',
                scheme: 'pinduoduo',
                uri: url.replace('https://', '')
            });
            break;
        default:

    }
}

var getTaoBaoShopClickUrl = function(shopuserid, shopid) {
    shopid = shopid || '58501945';
    var shopurl = 'http://store.taobao.com/shop/view_shop.htm?user_number_id=' + shopuserid;
    openWinto('web_view_win', 'widget://html/web_view_head', {
        url: shopurl
    });
}

function copyWord(text, tip) {
    tip = tip === false ? false : true;
    var clipBoard = api.require('clipBoard');
    clipBoard.set({
        value: text
    }, function(ret, err) {
        if (ret) {
            if (tip === true) {
                showToast('复制成功!');
            }
        }
    });
}

function getJdPddUrl(param, cb) {
    param.apiname = param.apiname || 'jd/getunionurl';
    var url = _URL + param.apiname;
    postData(url, {
        goods_id: param.goods_id,
        goods_sign: param.goods_sign,
        generate_authority_url: true,
        couponurl: param.couponurl, //京东优惠券链接
        positionid: isLoginOr().relation_id ? isLoginOr().relation_id : '186289',
        type: param.type, //京东类型	type=1 goods_id=商品ID，type=2 goods_id=店铺id，type=3 goods_id=自定义链接(京东活动链接、二合一链接)
        mall_id: param.mall_id, //拼多多店铺id
    }, function (ret, err) {
        // console.log(JSON.stringify(ret));
        // console.log(JSON.stringify(err));
        if (ret) {
            if (ret.status_code == 200) {
                typeof cb == 'function' & cb(ret);
            } else {
                showToast(TipInfo.data_fail);
            }
        } else {
            showToast(TipInfo.data_busy);
        }
    })
}
//好京客商品接口
function getGoodsListByHaoJingKe(apiname, param, cb, more, tmpl_id, div_id) {
    param.dataisend = param.dataisend ? param.dataisend : sorts_data.dataisend || false;
    if (param.dataisend === true) {
        return false;
    }
    $(".temporarily_data").hide();
    $(".index_loading").show();
    more = more || false;
    tmpl_id = param.tmpl_id || 'tmpl_goods_list';
    div_id = param.div_id || 'div_goods_list';
    apiname = apiname || 'jd/goodslist';
    param.pageindex = param.pageindex || 1;
    param.pagesize = param.pagesize || sorts_data.back;
    param.output = param.output || true;
    var url = '';
    for (var i in param) {
        url += i + '=' + param[i] + '&';
    }
    url = (app_SetInfo.url_pingtai.haojingke + url).replace('#apiname#', apiname);
    getData(url, function(ret, err) {
        if (ret) {
            // console.log(JSON.stringify(err));
            if (ret.data.status_code == 200) {
                $(".temporarily_data").hide();
                $(".index_loading").hide();
                if (param.output === true) { //是否需要渲染模板
                    if (true === more) {
                        var list_data = new Array;
                        var temp_id = $api.byId(tmpl_id);
                        var tmpdata = doT.template($api.text(temp_id));
                        list_data = list_data.concat(ret.data.data);
                        $api.append($api.byId(div_id), tmpdata(list_data));
                    } else {
                        setDotTmpl(tmpl_id, div_id, ret.data.data);
                        echo.render();
                    }
                } else {
                    typeof cb == 'function' && cb(ret, err);
                }
            } else {
                sorts_data.dataisend = true;
                $(".index_loading").hide();
                if (param.pageindex == 1) {
                    $(".temporarily_data").show();
                } else {
                    $(".index_loading img").hide();
                    $(".index_loading span").html("<div style='padding-left:30px;color:#dddddd'>—这是我的底线—</div>");
                    $(".index_loading").show();
                }
            }
        } else {
            showToast(TipInfo.data_busy);
        }
    });
}
//生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 0;
            break;
    }
}

function isNumber(val) {

    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) && regNeg.test(val)) {
        return true;
    } else {
        return false;
    }

}
//转换万单位
function changeW(x) {
    //if(!isNumber(x))
    //  return x;
    //if(!x) return x;
    x = parseInt(x * 1);
    if (x < 10000)
        return x;
    x = x / 10000;
    x = x.toFixed(1);
    var y = x + "万";
    return y;
}

function changeGooditem(info) {
    var item = {
        itemid: info.tao_id,
        itempic: 'http:' + info.pict_url,
        itemtitle: info.title,
        couponmoney: info.coupon_info_money,
        commissionrate: info.commission_rate, //佣金比例
        itemprice: info.zk_final_price,
        sellnum: info.volume,
        newprice: Decimal2(info.zk_final_price - info.coupon_amount), //计算卷后价格
        shoptype: info.user_type == '1' ? 'B' : 'C', //0表示集市，1表示商城
        couponstarttime: fmtDate(info.coupon_start_time),
        couponendtime: fmtDate(info.coupon_end_time)
    };
    if (app.isdebug == true) {
        console.log('商品信息:' + JSON.stringify(item));
    }
    return item;
}

//获取淘口令
function getTaoKouLing_(param, cb) {
    getDataApiTwo({
        apiname: 'open_tkl_create.ashx',
        text: encodeURI(param.app_name + '粉丝福利'),
        url: encodeURI(param.url),
        signurl: 0,
        post: true
    }, function(ret, err) {
        if (ret && ret.status == 200) {
            typeof cb == 'function' && cb(ret);
        } else {
            showToast('淘口令生成失败!');
        }
    });
}

function hasPermission() {
    var resultList = api.hasPermission({
        list: ['storage', 'photos', 'notification']
    });

    if (!resultList[0].granted || !resultList[1].granted) {
        api.requestPermission({
            list: ['storage', 'camera', 'photos'],
            code: 1
        }, function(ret, err) {

        });
    } else if (!resultList[2].granted) {
        api.requestPermission({
            list: ['notification'],
            code: 1
        }, function(ret, err) {

        });
    }
}

function openlayer(data) {
    api.openFrame({
        name: 'layer',
        url: 'widget://html/layer.html',
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto',
            marginTop: 0,
            marginLeft: 0
        },
        pageParam: {
            layername: data.layername || 'authtaobao'
        },
        bounces: false,
        bgColor: data.bgcolor || 'rgba(0,0,0,0.0)',
        useWKWebView: true,
        animation: {
            type: data.animtype || "movein", //动画类型（详见动画类型常量）
            subType: data.animsubtype || "from_top", //动画子类型（详见动画子类型常量）
            duration: 300 //动画过渡时间，默认300毫秒
        }

    });
}
//淘宝授权
function authTaoBaoQuDao(auth) {
    showProgress();
    getUserAllInfo(function(ret, err) {
        hideProgress();
        if (!ret.data.relation_id) {
            openlayer({
                layername: 'authtaobao'
            });
        } else {
            if (auth) {
                openCoupon();
            } else {
                getShareGoodsPic();
            }

        }
    })

}
//百川接口
var fun = {};
fun.bc = {};
fun.bc.init = function(cb) {
    var alibaichuan = api.require('baichuan');
    var param = {
        pid: appSetInfo.qdpid
    };
    alibaichuan.init(param, function(ret, err) {
        typeof cb == 'function' && cb(ret, err);
    });
}
fun.bc.login = function(callback) {
    var alibaichuan = api.require('baichuan');
    if (alibaichuan.is_instll() === false) {
        return;
    }
    alibaichuan.showLogin({
        openType: 1
    }, function(ret, err) {
        if (ret.code == 0) {
            typeof callback == 'function' && callback(ret, err);
        } else {
            showToast('登录失败!')
        }

    });
}
fun.bc.logout = function() {
    var alibaichuan = api.require('baichuan');
    if (alibaichuan.is_instll() === false) {
        return;
    }
    alibaichuan.logout(function(ret, err) {
        if (ret) {
            //showToast("退出成功");
        } else {
            showToast("退出失败:" + JSON.stringify(err));
        }
    });
}
fun.bc.showTaobaopage = function(url) {
    var baichuan = api.require('baichuan');
    if (baichuan.is_instll() === false) {
        showToast('未安装手淘!');
        return;
    }
    var relation_id = isLoginOr().relation_id || '';
    baichuan.showUrlPage({
        url: url + '&relationId=' + relation_id
    }, function(ret) {
        console.log(JSON.stringify(ret));
    });
}
fun.bc.auth = function(userid) {
        var alibaichuan = api.require('baichuan');
        if (alibaichuan.is_instll() === false) {
            showToast('未安装手淘!');
            return;
        }
        if (appSetInfo.taobaotype == 2 && appSetInfo.hysqtype == 1) { //百川模式打开淘宝api授权
            url = "https://oauth.m.taobao.com/authorize?response_type=code&client_id=" + appSetInfo.taobaoappid + "&redirect_uri=" + API_URL + "getTaoBaoQuDaoId/&state=" + userid;
        }
        alibaichuan.getUserInfo(function(ret, err) {
            if (ret) {
                //用户已经登录
                // console.log(ret.topAccessToken);
                fun.bc.showTaobaopage(url);

            } else {
                //淘宝授权 获取 code
                fun.bc.login(function(ret, err) {
                    if (ret) {
                        fun.bc.showTaobaopage(url);
                    } else {
                        showToast(err.msg);
                    }
                });
            }
        });

    }
    //淘宝活动转链id:活动id,openbybc是否百川手淘打开，url转链失败打开的url
function getTaoBaoHuoDongUrl(id, openbybc, url) {
    var relation_id = isLoginOr().relation_id || '';
    openbybc = openbybc || 'openbybc';
    url = url || 'https://m.taobao.com';
    showProgress();
    getDataApiTwo({
        apiname: 'open_activitylink_get.ashx',
        site_id: (appSetInfo.qdpid).split('_')[2],
        adzone_id: (appSetInfo.qdpid).split('_')[3],
        promotion_scene_id: id,
        platform: 2,
        relation_id: isLoginOr().relation_id
    }, function(ret, err) {
        hideProgress();
        console.log(JSON.stringify(ret));
        console.log(JSON.stringify(err));
        if (ret.tbk_sc_activity_info_get_response.data.short_click_url) {
            openindexfenleiurl_new(ret.tbk_sc_activity_info_get_response.data.click_url, openbybc);
        } else {
            openindexfenleiurl_new(url + '?relationId=' + relation_id);
        }
    });
}

//vip 转链
function openVipUrl(url, cb) {
    showProgress();
    postData(_URL + 'Vip/getunionurl', {
        apiname: 'url_privilege',
        relation_id: isLoginOr().relation_id,
        url: url
    }, function(ret, err) {
        console.log(JSON.stringify(ret));
        hideProgress();
        if (ret.code == 1) {
            if (typeof cb == "function") {
                cb(ret, err);
            } else {
                openindexfenleiurl_new(ret.data.noEvokeUrl);
            }
        }
    })
}

function xieyi(id) {

    openWinto('help_win', 'widget://html/common_head', {
        name: id == 52 ? '服务协议' : '隐私政策',
        url: _URL + 'help/red/artid/' + id
    });
}
//懒加载图片
function imgload() {
    var _init = function() {
        var _loadImgNodes = document.querySelectorAll('[data-echo]');
        if (_loadImgNodes.length) {
            for (var i = 0; i < _loadImgNodes.length; i++) {
                if (_loadImgNodes[i].getBoundingClientRect().top <= window.innerHeight && _loadImgNodes[i].getBoundingClientRect().left <= window.innerWidth) {
                    _loadImgNodes[i].src = _loadImgNodes[i].getAttribute('data-echo');
                    _loadImgNodes[i].removeAttribute("data-echo");
                }
            }
        }
    }
    _init();
    window.addEventListener('scroll', function() {
        _init();
    }, false);
}
